package org.jeecg.modules.cascv.image.service.merge.liutigui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import com.NativeImageIO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.BayerUtil;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 */
//TGMTYY1301_06BH_31_FPRAPP4
@Slf4j
@Service

public class LiutiguiApp4Service extends ImageService {
    @Value("${imageurl}")
    private String imageurl;
    public static String frames_field = "A1_FPR_MICU_APP4DATA_27_2021_1";
    public static String imageNum_field = "A1_FPR_MICU_APP4DATA_22_25_1";
    @Autowired
    private TaskExecutePool taskExecutePool;


    @Override
    public String idsNames() {
        return "TGMTYY1301_06BH_31_FPRAPP4,6D23H_2FH,6D23H_2FH_UDP";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {

        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }

        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String nextImageNum = conJson.getString(imageNum_field);
        String dataFrames = conJson.getString(frames_field);
        nextImageNum = nextImageNum.split(";")[0];
        dataFrames = dataFrames.split(";")[1].substring(2).trim();
        //dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        StringBuilder queue = LaptopConstant.imageData.get(key);

        composite(idsName, key, conJson, dataFrames, queue, nextImageNum, secondStr, subSecondStr);


        return null;
    }

    //TGMTYY1301_06BH_31_FPRAPP4
    public boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String currImageNum, String secondStr, String subSecondStr) {


        String lastImageNum = LaptopConstant.imageNumMap.get(key);

        //获取宽度  640
        //   int width = Integer.parseInt((content.getString(width_field)).split(";")[0]);
        //获取高度  512
        //   int height = Integer.parseInt((content.getString(height_field)).split(";")[0]);

        //System.out.println("imageNum=" + lastImageNum);
        //System.out.println("nextImageNum=" + currImageNum);

        if (lastImageNum == null || lastImageNum.equals(currImageNum)) {
            if (queue != null) {
                queue.append(dataFrames);
                LaptopConstant.imageData.put(key, queue);
            } else {
                queue = new StringBuilder();
                LaptopConstant.imageData.put(key, queue);
                queue.append(dataFrames);
            }
        } else {
            String imgHexStr = LaptopConstant.imageData.get(key).toString();

            if (imgHexStr.length() / 2 >= 640 * 512) {
                CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                    long start = System.currentTimeMillis();
                    byte[] bytes = HexUtil.decodeHex(imgHexStr);


                        int[] bgrArray = new int[bytes.length / 2];
                        TreeSet<Integer> bgrSet = new TreeSet<>();
                        for (int i = 0; i < bytes.length; i++) {
                            byte aByte = bytes[i];
                            i = i + 1;
                            if (i > bytes.length - 1) {
                                break;
                            }
                            byte bByte = bytes[i];      //0xff： 1111 1111
                            int a = aByte & 0xff;  // &:任何二进制位和0进行&运算，结果都是0；和1进行&运算结果都是原值
                            int b = bByte & 0xff; // <<:左位移 空位补0，被移除的高位丢弃
                            int v = b << 8 | a; // | :任何二进制位和0进行|运算，结果都是原值；和1进行|运算结果都是1
                            //向左移8位 空位补0 然后进行|运算 与a的二进制进行运算 与0相比就是原值 与1相比 就是1
                            bgrArray[i / 2] = v;
                            bgrSet.add(v);
                        }

                        int max = 0;
                        int min = 0;
                        if (bgrSet.size() > 20) {
                            for (int i = 0; i < 10; i++) {
                                max = bgrSet.pollLast();
                            }
                            for (int i = 0; i < 10; i++) {
                                min = bgrSet.pollFirst();
                            }
                        } else {
                            max = bgrSet.pollLast();
                            min = bgrSet.pollFirst();
                        }

                        byte[] newArray = new byte[bgrArray.length];
                        int cha = max - min;
                        for (int i = 0; i < bgrArray.length; i++) {
                            int v = bgrArray[i];
                            if (v > max) {
                                v = max;
                            } else if (v < min) {
                                v = min;
                            }

                            newArray[i] = (byte) ((v - min) * 255 / cha);
                        }

                        String idStr = IdWorker.getIdStr();
                        int png = LaptopConstant.nativeImageIO.write(newArray, 640, 512, "/data/images/", idStr + ".png", "png");

                        //base64生成图片的方式   String base64 = Base64.getEncoder().encodeToString(FileUtil.readBytes("/data/" + idStr + ".png"));
                        String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                        // http://10.2.28.192:3000/jeecg-boot/test/gmvVideo/getImage/1614863077934010370.png
                        content.put("imageUrl", imageUrl);
                        content.put("idsName", idsName);
                        //     String secondStr = content.getString("A1_FPR_MICU_APP4DATA_8_11_1").split(";")[1];
                        //    String subSecondStr = content.getString("A1_FPR_MICU_APP4DATA_12_13_1").split(";")[1];
                        content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                        String[] split = secondStr.split(":");
                        content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                        content.put("key", key);

                    log.info("流体柜6D23H_2FH, 合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                        return content;
                    },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);
            }
            queue = new StringBuilder();
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);
        }
        LaptopConstant.imageNumMap.put(key, currImageNum);
        return true;
    }


    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("D:\\pc_workspace\\流体物理实验柜1301\\红外热像仪数据.txt");
        LiutiguiApp4Service liutiguiApp4Service = new LiutiguiApp4Service();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            liutiguiApp4Service.merge(jsonObject, "TGMTYY1301_06BH_31_FPRAPP4", "TGMTYY1301_06BH_31_FPRAPP4");
        }

    }


}
